package com.shlh.saas.common;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;

@Component
public class Desensitization {
    // 邮箱脱敏方法（支持国际邮箱格式）
    public String maskEmail(String email) {
        if (email == null || email.isEmpty()) return email;

        if (email.contains(",")){
            String[] emails = email.split(",");
            StringBuilder result = new StringBuilder();
            for (String emailStr : emails) {
                result.append(getEmailString(emailStr)).append(",");
            }
            return result.substring(0, result.length() - 1);
        } else {
            return getEmailString(email);
        }
    }

    @NotNull
    private static String getEmailString(String email) {

        // 查找@符号位置
        int atIndex = email.indexOf('@');
        if (atIndex <= 0) {
            // 无效邮箱格式：直接保留前2个字符
            return email.length() > 2 ?
                    email.substring(0, 2) + "***" :
                    email + "***";
        }

        // 提取用户部分和域名
        String username = email.substring(0, atIndex);
        String domain = email.substring(atIndex + 1);

        // 用户名脱敏：保留前2个字符
        String maskedUsername;
        if (username.length() <= 2) {
            maskedUsername = username.charAt(0) + "***";
        } else {
            maskedUsername = username.substring(0, 2) + "***";
        }

        return maskedUsername + "@" + domain;
    }

    // 电话脱敏方法
    public String maskPhone(String phone) {
        if (phone == null || phone.isEmpty()) return phone;

        if (phone.contains(",")) {
            String[] phones = phone.split(",");
            StringBuilder result = new StringBuilder();
            for (String phoneStr : phones) {
                result.append(getPhoneString(phoneStr)).append(",");
            }
            return result.substring(0, result.length() - 1);
        } else {
            return getPhoneString(phone);
        }
    }

    @NotNull
    private static String getPhoneString(String phone) {
        // 分离国家区号和本地号码
        String countryCode = "";
        String localNumber = phone;

        // 识别国际区号模式（以+开头或00开头）
        if (phone.startsWith("+")) {
            int firstSpace = phone.indexOf(' ');
            if (firstSpace > 0) {
                countryCode = phone.substring(0, firstSpace);
                localNumber = phone.substring(firstSpace).trim();
            }
        } else if (phone.startsWith("00")) {
            int firstSpace = phone.indexOf(' ');
            if (firstSpace > 0) {
                countryCode = "+" + phone.substring(2, firstSpace);
                localNumber = phone.substring(firstSpace).trim();
            }
        }

        // 处理本地号码中的分隔符
        char[] chars = localNumber.toCharArray();
        int digitCount = 0;

        // 首先计算有效数字数量
        for (char c : chars) {
            if (Character.isDigit(c)) digitCount++;
        }

        // 数字太少时特殊处理
        if (digitCount <= 4) {
            return countryCode + "****" + (digitCount > 0 ?
                    localNumber.substring(localNumber.length() - digitCount) : "");
        }

        // 构建脱敏号码（保留最后4位数字）
        StringBuilder result = new StringBuilder(countryCode);
        int keepCount = 4;

        for (char c : chars) {
            if (Character.isDigit(c)) {
                if (digitCount <= keepCount) {
                    result.append(c);
                } else {
                    result.append('*');
                }
                digitCount--;
            } else {
                result.append(c);  // 保留非数字分隔符
            }
        }

        return result.toString();
    }

    // 网址脱敏方法
    public String maskWebAddress(String url) {
        if (url == null || url.isEmpty()) return url;

        String cleanUrl = null;
        try {
            // 标准化处理：移除协议和路径参数
            cleanUrl = url
                    .replaceFirst("^(https?://)?(www\\.)?", "")  // 去除协议和www
                    .split("\\?|/")[0];

            // 分离域名和顶级域名
            String[] parts = cleanUrl.split("\\.");
            if (parts.length == 0) return url;

            // 处理主域名部分
            String maskedDomain = maskDomainPart(parts[0]);

            // 构建最终域名（保留所有.分隔的顶级域名）
            StringBuilder result = new StringBuilder(maskedDomain);
            for (int i = 1; i < parts.length; i++) {
                result.append(".").append(parts[i]);
            }

            return result.toString();
        } catch (Exception e) {
            // 异常处理：简单保留首尾字符
            return cleanUrl.length() > 4 ?
                    cleanUrl.substring(0, 2) + "***" + cleanUrl.substring(cleanUrl.length() - 2) :
                    "****";
        }
    }

    // 域名部分脱敏辅助方法
    private String maskDomainPart(String domainPart) {
        if (domainPart.length() <= 4) {
            return domainPart.charAt(0) + "***";
        } else if (domainPart.length() <= 8) {
            return domainPart.substring(0, 2) + "***" + domainPart.substring(domainPart.length() - 2);
        } else {
            return domainPart.substring(0, 3) + "***" + domainPart.substring(domainPart.length() - 3);
        }
    }
}
